#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import os, curses, sys

class TreeFile :
	path = ""
		
	def __init__ (self, level, cfile, pTreeFile=None, tabs="") :
		self.level = level
		self.cfile = cfile
		self.pTreeFile = pTreeFile
		self.path = (pTreeFile.path + "/" if (pTreeFile != None and pTreeFile.path != "") else "") + cfile
		self.isdir = os.path.isdir(self.path)
		self.name = tabs + ("+ " if (self.isdir) else "- ") + cfile
		self.opened = False

def lsTree (cdir, lineNb=0) :	
	global fout
	tabs = ""
	for i in range(cdir.level+1) :
		tabs += TAB
	files = os.listdir(cdir.path)
	for f in files :
		if (lineNb > maxyx[0] - 1) : 
			break
		stdscr.move(lineNb, 0)
		if (f.startswith('.')) :
			continue
		tf = TreeFile(cdir.level+1, f, cdir, tabs) 
		lines.insert(lineNb, tf);
		stdscr.insertln()
		stdscr.addstr(lineNb, 0, tf.name)
		lineNb += 1

def refreshCurrentLine () :
	global oldLine, fout
	if (oldLine == maxyx[0] - 1) :
		stdscr.addnstr(oldLine, 0, stdscr.instr(oldLine, 0), maxyx[1]-1)
	else : 
		stdscr.addstr(oldLine, 0, stdscr.instr(oldLine, 0))
	stdscr.redrawln(oldLine, 0)
	if (currentLine == maxyx[0] - 1) :
		stdscr.addnstr(currentLine, 0, stdscr.instr(currentLine, 0), maxyx[1]-1, curses.A_REVERSE)
	else :
		stdscr.addstr(currentLine, 0, stdscr.instr(currentLine, 0), curses.A_REVERSE)
	stdscr.redrawln(currentLine, 0)
	oldLine = currentLine
	#stdscr.refresh()
	
def openCurrentFile () :
	if (not lines[currentLine].isdir) :
		curses.flash()	
	else :
		if (not lines[currentLine].opened) : 
			lsTree(lines[currentLine], currentLine + 1)
			lines[currentLine].opened = True
		else :
			curses.flash()
	
def handleKey (char) :
	global currentLine
		
	if (char == curses.KEY_DOWN and currentLine < maxyx[0] - 1) :
		currentLine += 1
	elif (char == curses.KEY_UP and currentLine > 0) :
		currentLine -= 1
	elif (char == curses.KEY_RIGHT) :		
		openCurrentFile()
	
def finish () :
	curses.nocbreak(); 
	stdscr.keypad(0);
	curses.echo()
	curses.endwin()

#----------------------------------------------				
#========== MAIN ==============================
#----------------------------------------------
TAB = "|    "

stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
curses.curs_set(0)
stdscr.keypad(1)
maxyx = stdscr.getmaxyx()

lines = []
c = ''
currentLine = 0
oldLine = 0
if (len(sys.argv) > 1) :
	rootTreeFile = TreeFile(-1, sys.argv[1])
else :
	rootTreeFile = TreeFile(-1, ".")
#fout = open("tree.txt", "w")

lsTree(rootTreeFile)
while (c != ord('q')) :
	refreshCurrentLine()
	c = stdscr.getch()
	handleKey(c)

#fout.close()
finish()
